var ver = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/ // valid email regular expression

$(document).ready(function() {
  $(".on-enter-key-blur").keypress(function(event) {
    if (event.keyCode == 13) {
      $(this).blur();
      event.preventDefault();
    }
  });
});

var item = {
  data_map : {},

  init : function(object) {
    this.data_map = object;
  },

  editName : function(item_id) {
    var name = $("textarea#name")[0];
    if (name && name.value.length > 0) {
      this.editProperty(item_id, "name", name.value);
      $("textarea#name").hide();
      $("span.item-name")[0].innerHTML = name.value;
      $("span.item-name,a.edit-item-name").show();
    }
  },

  editReading : function(item_id) {
    var tar = $("textarea#reading");
    tar.hide();
    if (tar[0].value.length > 0) {
      $("span.item-reading")[0].innerText = tar[0].value;
      this.editProperty(item_id, "reading", tar[0].value);
    }
    $("span.item-reading, a.edit-item-reading").show();
  },

  editProperty : function(test_id, property_name, property_value) {
    $.ajax({
      url : "/item/edit_property?id=" + test_id +
        "&property_name=" + property_name + "&property_value=" + property_value,
      type : "post",
      success : function() {
//        alert("success!");
      }
    });
  }
};

function validate(form) {
  var ri = form.find("[validation='required']");
  var errors = 0;
  ri.each(function() {
    if (this.value.length == 0) {
      $(this).addClass("error");
      errors++;
    } else if (this.name == "email" && !ver.test(this.value)) {
      $(this).addClass("error");
      alert("Invalid email");
      errors++;
    } else {
      $(this).removeClass("error");
    }
  });
  if (errors > 0) {
    var first = $(".error")[0].focus();
  }
  return errors == 0;
}

function loadJavaScript(name, callback) {
  var url = "/js/" + name + ".js";
  $("script#async").load(url, function() {
    callback();
  });
}

CanvasRenderingContext2D.prototype.clear = function() {
  this.clearRect(0, 0, this.canvas.width, this.canvas.height);
}

function hideDivs(divs) {
  for (var i = 0; i < divs.length; i++) {
    $(divs[i]).hide();
  }
}

function shuffle(array) {
  var shuffled = [];
  while (shuffled.length < array.length) {
    var item = array[Math.floor(Math.random() * array.length)];
    if ($.inArray(item, shuffled) < 0) {
      shuffled.push(item);
    }
  }
  return shuffled;
}

HTMLCanvasElement.prototype.mouseCoordinates = function(event) {
    var offset = { "x" : 0, "y" : 0 };
    var currentElement = this;

    do{
      offset.x += currentElement.offsetLeft;
      offset.y += currentElement.offsetTop;
      if (currentElement.tagName != "BODY") {
        offset.x -= currentElement.scrollLeft;
        offset.y -= currentElement.scrollTop;
      }
    }
    while(currentElement = currentElement.offsetParent);

    return { x : event.pageX - offset.x, y : event.pageY - offset.y}
}